package cn.itsource.pethome.config;

import cn.itsource.pethome.annotation.PreAuthorize;
import cn.itsource.pethome.jwt.Payload;
import cn.itsource.pethome.jwt.PayloadData;
import cn.itsource.pethome.utils.JwtUtils;
import cn.itsource.pethome.utils.RsaUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.Date;
import java.util.Set;

/**
 * @Author:R
 * @Date:2023/1/13 19:51
 * Description  登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final String MSG = "{\"success\":false,\"msg\":\"noLogin\"}";
    private final String NO_PERMISSION = "{\"success\":false,\"msg\":\"noPermission\"}";
    @Resource
    private RedisTemplate redisTemplate;
    @Value("${jwt.rsa.pub}")
    private String pub;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("Token");
        if(token == null) {
            sendErro(response, MSG);
            return false;
        }
        //2.获取公钥，解析token
        PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(pub).getFile());
        Payload<PayloadData> payLoad = null;
        try {
            payLoad = JwtUtils.getInfoFromToken(token, publicKey, PayloadData.class);
        }catch (Exception e){//如果解析出错，就代表超时或者其他问题，不放行
            sendErro(response,MSG);
            return false;
        }
        //3.刷新token过期时间
        Date expiration = payLoad.getExpiration();
        DateTime refreshTime = new DateTime(expiration).minusMinutes(5);//过期前5分钟
        //当前时间在刷新时间之后就要刷新一把
        if(refreshTime.isBefore(DateTime.now())){
            sendErro(response,MSG);
            return false;
        }
        //4.获取权限    权限为空的拦截
        Set<String> permissions = payLoad.getUserInfo().getPermissions();
        //5.权限校验     哪些请求需要校验权限 （答：打了自定义注解PreAuthorize权限的方法）
        if (handler instanceof  HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
            //preAuthorize 无值代表是公共资源，访问不需要权限，放行
            if(preAuthorize == null)
                return true;
            //6. preAuthorize 有值，校验是否有权限访问
            String sn = preAuthorize.value();//需要校验当前登录人，是否有权限访问该资源
            if(!permissions.contains(sn)){
                sendErro(response, NO_PERMISSION);
                return false;
            }
        }
        return true;
    }

    private void sendErro(HttpServletResponse response,String msg) throws IOException {
        //告诉前端错误信息 {“success”:false,"message":"noLogin"}，让前端跳转页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(msg);
        writer.close();
    }
}
